package concurrecy.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 信号量的实现
 */
public class JannaSemaphore {

    private final int permits;
    private final Sync sync = new Sync();

    public JannaSemaphore(int permits) {
        this.permits = permits;
    }

    public void acquire() {
        sync.acquireShared(1);
    }

    public void release() {
        sync.releaseShared(1);
    }

    private class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected int tryAcquireShared(int arg) {
            int s, next;
            do {
                s = getState();
                next = s + arg;
                if(next > permits)
                    return -1;
            } while(!compareAndSetState(s, next));
            return 1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            int s, next;
            do {
                s = getState();
                next = s - arg;
            } while(!compareAndSetState(s, next));
            return true;
        }
    }
}


class SemaphoreTask1 implements Runnable {
    private JannaSemaphore semaphore;
    private static int count = 0;
    private final int id = count ++;

    public SemaphoreTask1(JannaSemaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public String toString() {
        return "Task" + id;
    }

    @Override
    public void run() {
        try {
            System.out.println(this + " ready acquire semaphore");
            semaphore.acquire();
            System.out.println(this + " acquire a semaphore");
            try {
                TimeUnit.SECONDS.sleep(1);
            } finally {
                semaphore.release();
                System.out.println(this + " release a semaphore");
            }
        } catch (InterruptedException e) {
            System.out.println(this + " interrupted");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final JannaSemaphore semaphore = new JannaSemaphore(10);
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; i++) {
            service.execute(new SemaphoreTask1(semaphore));
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println("shutdown");
//        service.shutdownNow();
        service.shutdown();
    }
}